<?php
namespace Common\Logic\Common;

use Common\Base\LogicBase;
use Common\Model\Common\ConfigModel;

class ConfigLogic extends LogicBase
{
    public $m_config;
    public $_search_option = array();

    public function __construct()
    {
        $this->m_config = new ConfigModel();

        $this->_search_option = array(
            'catOptions' =>$this->getAllCate(),
            'typeOptions'=>array(
                1 => array('type'=>'text',     'val'=>'文本框', 'default'=>'文本框'),
                2 => array('type'=>'password', 'val'=>'密码框'),
                3 => array('type'=>'textarea', 'val'=>'文本域'),
                4 => array('type'=>'radio',    'val'=>'单选框'),
                5 => array('type'=>'checkbox', 'val'=>'复选框'),
                6 => array('type'=>'select',   'val'=>'下拉列表'),
                7 => array('type'=>'file',     'val'=>'文件上传'),
            ),
        );
    }

    /**
     * 返回搜索选项
     *
     * @return array
     */
    public function getSearchOption()
    {
        return $this->_search_option;
    }

    /**
     * 获取配置列表
     *
     * @return array 配置数组
     */
    public function getGlobalConfig()
    {
        $data = $this->m_config->getConfig();
        $cache = array();
        if(!empty($data) && is_array($data)){
            foreach ($data as $value) {
                $cache[strtoupper($value['name'])] = $value['value'];
            }
        }
        return $cache;
    }

    /**
     * 取得所有系统设置
     *
     * @return array
     */
    public function getAllConfig()
    {
        return $this->m_config->getAllConfig();
    }

    /**
     * 取得指定ID的系统设置
     *
     * @param int $config_id
     * @return array
     */
    public function getConfigById($config_id = 0)
    {
        return $this->m_config->getConfigById($config_id);
    }

    /**
     * 取得指定系统设置ID的子系统设置
     *
     * @param int $config_id
     *
     * @return array
     */
    public function getChildConfigById($config_id = 0)
    {
        return $this->m_config->getConfig(array('parent_id'=>(int)$config_id));
    }

    /**
     * 取得指定选项名的系统设置
     *
     * @param string $name
     *
     * @return array
     */
    public function getConfigByName($name = '')
    {
        return $this->m_config->getConfigByName($name);
    }

    /**
     * 取得所有系统分类及分类下的明细
     *
     * @return array
     */
    public function getAllCateConfig()
    {
        $configs = $this->getChildConfigById(0);
        $optionFrom = $this->getOptionFrom();
        $cate = array();
        if($configs)
        {
            foreach($configs as $k=>$config)
            {
                $config['config_id'] = intval($config['config_id']);
                $cate[$config['config_id']]['name'] = $config['name'];
                $cate[$config['config_id']]['title'] = $config['title'];
                $cate[$config['config_id']]['options'] = array();
                if( ! empty($optionFrom)){
                    if(array_key_exists($config['config_id'], $optionFrom)){
                        $cate[$config['config_id']]['options'] = $optionFrom[$config['config_id']];
                    }
                }
            }
        }
        return $cate;
    }


    /**
     * 取得所有系统设置分类
     *
     * @return array
     */
    public function getAllCate()
    {
        return $this->getChildConfigById(0);
    }

    /**
     * 取得系统设置并生成表单控件
     *
     * @return   array
     */
    public function getOptionFrom()
    {
        $options = $this->getAllConfig();
        $result = array();
        if ( ! empty($options)){
            foreach ($options as $option)
            {
                if($option['type'] != 'hidden'){
                    $result[$option['parent_id']][$option['config_id']] = array('title'=>$option['title'], 'config_id'=>$option['config_id'], 'notice'=>$option['notice']);
                }
                switch ($option['type'])
                {
                    case 'text':
                        $result[$option['parent_id']][$option['config_id']]['option'] = $this->buildText(array('name'=>$option['name'], 'value'=>$option['value']));
                        break;
                    case 'password':
                        $result[$option['parent_id']][$option['config_id']]['option'] = $this->buildPassword(array('name'=>$option['name'], 'value'=>$option['value']));
                        break;
                    case 'textarea':
                        $result[$option['parent_id']][$option['config_id']]['option'] = $this->buildTextArea(array('name'=>$option['name'], 'value'=>$option['value']));
                        break;
                    case 'radio':
                        $result[$option['parent_id']][$option['config_id']]['option'] = $this->buildRadio(array('name'=>$option['name'], 'checked'=>$option['value'], 'options'=>unserialize($option['type_options'])));
                        break;
                    case 'checkbox':
                        $result[$option['parent_id']][$option['config_id']]['option'] = $this->buildCheckbox(array('name'=>$option['name'], 'checked'=>$option['value'], 'options'=>unserialize($option['type_options'])));
                        break;
                    case 'select':
                        $result[$option['parent_id']][$option['config_id']]['option'] = $this->buildSelect(array('name'=>$option['name'], 'selected'=>$option['value'], 'options'=>unserialize($option['type_options'])));
                        break;
                    case 'file':
                        $result[$option['parent_id']][$option['config_id']]['option'] = $this->buildFile(array('name'=>$option['name'], 'file'=>$option['value'], 'options'=>unserialize($option['type_options'])));
                        break;
                }
            }
        }
        return $result;
    }


    /**
     * 添加/编辑系统设置
     *
     * @param array $data
     * @param int   $config_id
     *
     * @return int lastInsertId
     */
    public function editConfig($data=array(), $config_id=null)
    {
        if($data['name'] == ''){
            $this->setError('配置名称不能为空');
            return false;
        }
        if($data['title'] == ''){
            $this->setError('标题不能为空');
            return false;
        }
        $typeOptionExists = false;
        if($data['type'] == 'radio' || $data['type'] == 'checkbox' || $data['type'] == 'select'){
            $typeOptions = array();
            foreach($data['type_key'] as $key=>$value)
            {
                if(strlen($value)>0 && strlen($data['type_key'][$key])>0){
                    $typeOptionExists = true;
                    $typeOptions[$value] = $data['type_value'][$key];
                }
            }
            if($typeOptionExists == false){

                $this->setError('配置类型没有选');
                return false;
            }
            $data['type_options'] = serialize($typeOptions);
        }
        $config = $this->getConfigByName($data['name']);
        $result = 0;
        if($config_id == null){
            if($config){
                $this->setError('该配置已经存在');
                return false;
            }
            $row = array(
                'parent_id' => $data['parent_id'],
                'name' => $data['name'],
                'title' => $data['title'],
                'type' => $data['type'],
                'type_options' => $data['type_options'],
                'notice' => $data['notice']
            );
            $result = $this->m_config->add($row);
        }else{
            if ($config && $config['config_id'] != $config_id){
                $this->setError('该名称的配置已经存在');
                return false;
            }
            $exists = $this->getConfigById($config_id);
            if( ! $exists){
                $this->setError('该名称不存在');
                return false;
            }
            $set = array(
                'parent_id' => $data['parent_id'],
                'title' => $data['title'],
                'type' => $data['type'],
                'type_options' => $data['type_options'],
                'notice' => $data['notice']
            );

            if($config_id > 0){
                $result = $this->m_config->edit($config_id,$set);
            }
        }
        if (is_numeric($result) && $result >= 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新系统设置
     *
     * @param array $data
     * @param array $files
     *
     * @return array
     */
    public function updateConfig($data=array(), $files=array())
    {
        foreach($files as $file=>$info)
        {
            $config = $this->getConfigByName($file);
            if($data['delete_' . $file] == '1'){
                $data[$file] = '';
                @unlink($config['value']);
            }
            $imgData = upload_img($file, 'site');
            if($imgData['success']){
                @unlink($config['value']);
                $data[$file] = $imgData['url'];
            }
        }
        if($data){
            $this->m_config->update($data);
        }
        F('global_cfg', null);
    }


    /**
     * 根据ID删除数据
     *
     * @param int $config_id
     *
     * @return boolean
     **/
    public function deleteConfigById($config_id = 0)
    {
        if (false === $this->m_config->deleteConfigById($config_id)) {
            $this->setError($this->m_config->getError());
            return false;
        }
        return true;
    }




    /**
     * 创建文本框
     *
     * @param array $data
     *
     * @return string
     */
    public function buildText($data = array())
    {
        $data['size'] = isset($data['size']) ? $data['size'] : "30";
        $data['maxlength'] = isset($data['maxlength']) ? "maxlength=\"" . $data['maxlength'] . "\"" : "";
        $result = "<input type=\"text\" name=\"" . $data['name'] . "\" size=\"" . $data['size'] . "\" value=\"" . $data['value'] . "\" " . $data['maxlength'] . " class=\"form-control form-focus input_text\" />";
        return $result;
    }

    /**
     * 创建密码框
     *
     * @param  array $data
     *
     * @return string
     */
    public function buildPassword($data = array())
    {
        $data['size'] = isset($data['size']) ? $data['size'] : "30";
        $data['maxlength'] = isset($data['maxlength']) ? "maxlength=\"" . $data['maxlength'] . "\"" : "";
        $result = "<input type=\"password\" name=\"" . $data['name'] . "\" size=\"" . $data['size'] . "\" value=\"" . $data['value'] . "\" " . $data['maxlength'] . " class=\"form-control form-focus input_text\" />";
        return $result;
    }

    /**
     * 创建文本域
     *
     * @param array $data
     *
     * @return string
     */
    public function buildTextArea($data = array())
    {
        $data['width'] = isset($data['width']) ? $data['width'] : "400px";
        $data['height'] = isset($data['height']) ? $data['height'] : "50px";
        $result = "<textarea name=\"" . $data['name'] . "\" style=\"width: " . $data['width'] . ";height: " . $data['height'] . "\" class=\"form-control form-focus input_text\">" . $data['value'] . "</textarea>";
        return $result;
    }

    /**
     * 创建单选框
     *
     * @param array $data
     *
     * @return string
     */
    public function buildRadio($data = array())
    {
        $data['separator'] = isset($data['separator']) ? $data['separator'] : "<span style='padding-left:5px'></span>";
        $radio = array();
        foreach ($data['options'] as $key => $value)
        {
            $checked = ($data['checked'] == $key) ? "checked" : "";
            $radio[] = "<input type=\"radio\" name=\"" . $data['name'] . "\" value=\"" . $key . "\" " . $checked . " /> " . $value;
        }
        $result = implode($data['separator'], $radio);
        return $result;
    }

    /**
     * 创建复选框
     *
     * @param array $data
     *
     * @return string
     */
    public function buildCheckbox(array $data)
    {
        $data['separator'] = ($data['separator']) ? $data['separator'] : "<span style='padding-left:5px'></span>";
        $radio = array();
        foreach ($data['options'] as $key => $value)
        {
            $checked = ($data['checked'] == $key) ? "checked" : "";
            $radio[] = "<input type=\"checkbox\" name=\"" . $data['name'] . "[]\" value=\"" . $key . "\" " . $checked . " /> " . $value;
        }
        $result = implode($data['separator'], $radio);
        return $result;
    }

    /**
     * 创建下拉列表
     *
     * @param array $data
     *
     * @return string
     */
    public function buildSelect(array $data)
    {
        $option = array();
        foreach ($data['options'] as $key => $value)
        {
            $selected = ($data['selected'] == $key) ? "selected" : "";
            $option[] = "<option value=\"" . $key . "\" " . $selected . ">" . $value . "</option>";
        }
        $result = "<select name=\"" . $data['name'] . "\">" . implode('', $option) . "</select>";
        return $result;
    }

    /**
     * 创建文件上传组件
     *
     * @param array $data
     * @return string
     */
    public function buildFile(array $data)
    {
        $data['size'] = isset($data['size']) ? $data['size'] : "15";
        $data['file'] = isset($data['file']) ? "<i class=\"icon icon-picture\"></i> <input type=\"checkbox\" name=\"delete_" . $data['name'] . "\" value=\"1\" alt=\"删除\" /> 删除图片" :"";
        $result = "<input type=\"file\" name=\"" . $data['name'] . "\" size=\"" . $data['size'] . "\" />  " . $data['file'];
        return $result;
    }
}